package com.zdy.today.base;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.zdy.model.BaseBean;
import com.zdy.today.CallBack;
import com.zdy.today.Constant;
import com.zdy.today.R;
import com.zdy.widget.CustomProgressDialog;
import com.zdy.widget.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscription;

import static anetwork.channel.http.NetworkSdkSetting.context;

/**
 * Created by zdy on 2016/9/13.
 */
public abstract class BaseActivity extends AppCompatActivity {
    @BindView(R.id.loading)
    ContentLoadingProgressBar loading;
    @BindView(R.id.iv_left)
    ImageView iv_left;
    @BindView(R.id.title_left)
    TextView title_left;
    @BindView(R.id.title_middle)
    TextView title_middle;
    @BindView(R.id.title_right)
    TextView title_right;
    @BindView(R.id.tv_fail_des)
    TextView tv_fail_des;
    @BindView(R.id.rl_fail_loading)
    RelativeLayout rl_fail_loading;
    @BindView(R.id.ll_fail)
    LinearLayout ll_fail;
    @BindView(R.id.bt_reload)
    Button bt_reload;
    CustomProgressDialog progressDialog;
    Unbinder unbinder;

    public int netType;//访问网络的类型，0代表不访问
    protected Subscription subscribe;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushAgent.getInstance(context).onAppStart();
        initOnCreate(savedInstanceState);
        init();
    }

    public void initOnCreate(Bundle savedInstanceState) {
        setContentView(R.layout.layout_base);
        if (getResourceId() != 0)
            View.inflate(this, getResourceId(), (ViewGroup) findViewById(R.id.fl_content));
        unbinder = ButterKnife.bind(this);
        title_middle.setText(setTitle());
    }

    public void setTitleText(String text) {
        title_middle.setText(text);
    }

    @Override
    public void onBackPressed() {
        onFinish();
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (subscribe != null && !subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        super.onDestroy();
    }

    protected abstract void init();

    protected abstract String setTitle();

    protected void setLeft(String text, int bg, CallBack callBack) {
        if (bg != 0){
            Drawable drawable = getResources().getDrawable(bg);
            drawable.setBounds(0,0,drawable.getMinimumWidth(), drawable.getMinimumHeight());
            title_left.setCompoundDrawables(drawable, null, null, null);
        }
        if (bg == 0 && TextUtils.isEmpty(text)) {
            title_left.setVisibility(View.GONE);
        } else {
            title_left.setVisibility(View.VISIBLE);
            title_left.setText(text);
            title_left.setOnClickListener(v -> callBack.callBack());
        }
    }

    protected void setRight(String text, CallBack callBack) {
        title_right.setVisibility(View.VISIBLE);
        title_right.setText(text);
        title_right.setOnClickListener(v -> callBack.callBack());
    }


    protected void showLoadingDialog() {
        if (progressDialog == null) {
            progressDialog = new CustomProgressDialog(this);
        }
        progressDialog.show();
    }

    protected void hideLoadingDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    protected void showLoadingPage() {
        if (ll_fail.getVisibility() == View.VISIBLE)
            ll_fail.setVisibility(View.GONE);
        if (loading != null)
            loading.setVisibility(View.VISIBLE);
    }

    protected void hideLoadingPage() {
        if (loading != null)
            loading.setVisibility(View.GONE);
    }

    protected abstract int getResourceId();

    protected void reload() {
        showLoadingPage();
        askNetData();
    }

    protected void setEmptyView() {
        if (ll_fail.getVisibility() == View.GONE)
            ll_fail.setVisibility(View.VISIBLE);
        if (bt_reload != null)
            bt_reload.setVisibility(View.GONE);
        if (loading != null)
            loading.setVisibility(View.GONE);
        if (tv_fail_des != null)
            tv_fail_des.setText("暂无数据");
    }

    protected void setFailView(String failDes) {
        if (ll_fail.getVisibility() == View.GONE)
            ll_fail.setVisibility(View.VISIBLE);
        if (bt_reload != null)
            bt_reload.setVisibility(View.VISIBLE);
        if (loading != null)
            loading.setVisibility(View.GONE);
        if (tv_fail_des != null)
            tv_fail_des.setText(failDes);
    }

    @OnClick({R.id.bt_reload, R.id.title_left})
    public void onBaseClick(View v) {
        switch (v.getId()) {
            case R.id.bt_reload:
                reload();
                break;
            case R.id.title_left:
                onFinish();
                break;
        }
    }

    public void onFinish() {
        finish();
    }

    public void handlerSuccessDialog(BaseBean<? extends BaseBean> baseBean) {
        hideLoadingDialog();
        netType = 0;//当网络请求成功时，初始化网络访问的类型，默认为不访问,每次访问成功时初始化网络访问类型
    }

    public void handlerFailureDialog(Throwable throwable) {
        try {
            hideLoadingDialog();
            Logger.d(throwable);
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                Response response = httpException.response();
                ResponseBody responseBody = response.errorBody();
                Logger.d(response.code());
                String jsonContent = responseBody.string();
                Logger.d(jsonContent);
                BaseBean baseBean = new Gson().fromJson(jsonContent, BaseBean.class);
                ToastUtil.showToastShort(this, baseBean.getInfo());
            } else {
                ToastUtil.showToastShort(this, Constant.NETWORK_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToastShort(this, Constant.NETWORK_ERROR);
        }
    }

    //网络数据交互
    protected void askNetData(Object... params) {
        if (subscribe != null && !subscribe.isUnsubscribed())
            subscribe.unsubscribe();
    }

    //设置app内部字体不受系统字体改变的影响
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    protected int currentPage;

    public void handlerSuccessPage(BaseBean<? extends BaseBean> baseBean) {
        hideLoadingPage();
        if (netType == 1) {//下拉刷新
            addfirst(baseBean);
//            if (baseBean.getCount() == 0 && currentPage == 1) {
//                setEmptyView();
//            } else {
            if (tv_fail_des != null)
                tv_fail_des.setText("");
//            }
            addFirstData(baseBean);
        } else if (netType == 2) {//加载更多
            addMoreData(baseBean);
        }
        netType = 0;//当网络请求成功时，初始化网络访问的类型，默认为不访问,每次访问成功时初始化网络访问类型
    }

    PtrClassicFrameLayout ptrClassicFrameLayout;

    //设置下拉刷新加载更多监听
    public void setRefreshListener(PtrClassicFrameLayout ptrClassicFrameLayout) {
        this.ptrClassicFrameLayout = ptrClassicFrameLayout;
        ptrClassicFrameLayout.setLoadMoreEnable(false);
        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                loadData();
            }
        });
        ptrClassicFrameLayout.setOnLoadMoreListener(() -> loadMoreData());
        autoRefresh(ptrClassicFrameLayout);
    }

    //首入自动刷新
    public void autoRefresh(PtrClassicFrameLayout ptrClassicFrameLayout) {
        hideLoadingPage();
        ptrClassicFrameLayout.postDelayed(() -> ptrClassicFrameLayout.autoRefresh(true), 150);
    }

    public void addMoreData(BaseBean<? extends BaseBean> baseBean) {
        addmore(baseBean);
    }

    private void addmore(BaseBean<? extends BaseBean> baseBean) {
        if (ptrClassicFrameLayout != null) {
            ptrClassicFrameLayout.loadMoreComplete(true);
//            if (TextUtils.isEmpty(baseBean.getNext())) {
            ptrClassicFrameLayout.setLoadMoreEnable(false);
//            } else {
//                ptrClassicFrameLayout.setLoadMoreEnable(true);
//            }
        }
    }

    public void addFirstData(BaseBean<? extends BaseBean> baseBean) {
    }

    private void addfirst(BaseBean<? extends BaseBean> baseBean) {
        if (ptrClassicFrameLayout != null) {
            ptrClassicFrameLayout.refreshComplete();
//            if (TextUtils.isEmpty(baseBean.getNext())) {
            ptrClassicFrameLayout.setLoadMoreEnable(false);
//            } else {
//                ptrClassicFrameLayout.setLoadMoreEnable(true);
//            }
        }
    }

    private void refreshComplete() {
        if (ptrClassicFrameLayout != null) {
            ptrClassicFrameLayout.refreshComplete();
            if (netType == 2)
                ptrClassicFrameLayout.loadMoreComplete(true);
        }
    }

    public void handlerFailurePage(Throwable throwable) {
        try {
            hideLoadingPage();
            Logger.d(throwable);
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                Response response = httpException.response();
                ResponseBody responseBody = response.errorBody();
                Logger.d(response.code());
                String jsonContent = responseBody.string();
                Logger.d(jsonContent);
                BaseBean baseBean = new Gson().fromJson(jsonContent, BaseBean.class);
                setLoadPageFail(baseBean.getInfo());
            } else {
                setLoadPageFail(Constant.NETWORK_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            setLoadPageFail(Constant.NETWORK_ERROR);
        }
    }

    private void setLoadPageFail(String msg) {
        refreshComplete();
        if (hasData()) {
            ToastUtil.showToastShort(this, msg);
        } else {
            setFailView(msg);
        }
    }

    public boolean hasData() {
        return false;
    }

    private void loadData() {
        netType = 1;
        currentPage = 1;
        askNetData();
    }


    private void loadMoreData() {
        netType = 2;
        currentPage++;
        askNetData();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
